package commandmode.controller;

import commandmode.base.BaseCommand;
import commandmode.impl.NoCommandImpl;

import java.util.ArrayList;


/**
 * 遥控器
 * 可扩展插槽的遥控器
 *
 * @author yaojianfeng
 */
public class RemoteControl {
    /**
     * 遥控器可能处理多个开与关的命令,使用相应的数组记录这些命令
     */
    BaseCommand[] onCommands;
    BaseCommand[] offCommands;
    /**
     * 新增一个实例变量 用来记录上一步是什么
     */
    BaseCommand undoCommand;

    /**
     * 在构造器中实例化并初始化这两个开与关的数组
     * 7个插槽 初始化为7
     *
     * @param i 遥控器插槽数量
     */
    public RemoteControl(int i) {
        this.onCommands = new BaseCommand[i];
        this.offCommands = new BaseCommand[i];
        /**
         * 初始化的时候 每个插槽上面都是空对象
         */
        BaseCommand command = new NoCommandImpl();
        for (int i1 = 0; i1 < i; i1++) {
            onCommands[i1] = command;
            offCommands[i1] = command;
        }
        /**
         * 一开始 撤销按钮什么也不做
         */
        undoCommand = command;
    }

    /**
     * 给插槽设置命令对象
     *
     * @param slotPosition 插槽位置
     * @param on           开命令对象
     * @param off          关命令对象
     */
    public void setCommands(int slotPosition, BaseCommand on, BaseCommand off) {
        onCommands[slotPosition] = on;
        offCommands[slotPosition] = off;
    }

    /**
     * 按下开按钮
     *
     * @param slotPosition 按钮位置
     */
    public void onButtonWasPressed(int slotPosition) {
        onCommands[slotPosition].execute();
        undoCommand = onCommands[slotPosition];
    }

    /**
     * 按下关按钮
     *
     * @param slotPosition
     */
    public void offButtonWasPressed(int slotPosition) {
        offCommands[slotPosition].execute();
        undoCommand = offCommands[slotPosition];
    }

    /**
     * 按下撤销按钮
     */
    public void undoButtonWasPressed() {
        undoCommand.undo();
    }

}
